#!/usr/bin/env python


import sys
import re
import shutil
import argparse

def get_args():
    parser = argparse.ArgumentParser(description='Programm to rename files '
                                     'with a Python regex.')
    parser.add_argument('regex', help='Regular expression which is used for '
                        'searching. Works exactly like Python regex.')
    parser.add_argument('replace',
                       help='Template for replacing. It uses the Python '
                       '.format() method to replace the positional arguments '
                       'from regex.')
    parser.add_argument('files', metavar='file', nargs='+',
                       help='Files which should be renamed.')
    parser.add_argument('-v', '--verbose', action='store_true',
                       help='Print file operations.')
    parser.add_argument('-n', '--dry_run', action='store_true',
                       help="Don't execute file operations.")
    
    return parser.parse_args()


if __name__ == '__main__':
    
    args = get_args()
    
    try:
        regex = re.compile(args.regex)
    except re.error, e:
        sys.exit("Regex Error: %s" % e[0])
    
    for filename in args.files:
        match = regex.match(filename)
        
        if match is None:
            continue
        
        destination = args.replace.format(*match.groups())
        
        if args.verbose is True:
            print '"%s" > "%s"' % (filename, destination)
        
        if args.dry_run is not True:
            shutil.move(filename, destination)
